//
//  JJLog.swift
//  swiftProject
//
//  Created by yangjian on 2021/12/18.
//

import UIKit



class JJLog : NSObject{
    private static let jj = JJLog.init()
    static func shared() -> JJLog{
        return jj;
    }
    static func write(_ any:Any){
        self.shared()._write(any)
//        return
//        self.shared().write(any)
    }
    
    let filePath = "\(NSHomeDirectory())/Library/Application Support/jj/log.txt"
    var logOutPutStream : OutputStream!
    var logData = [Data].init()
    var logging = false
    let dateformatter = DateFormatter()
    override init() {
        super.init()
        dateformatter.dateFormat = "YYYY-MM-dd HH:mm:ss:SSS"// 自定义时间格式
        var names = filePath.components(separatedBy: "/")
        names.removeLast()
        if directory_createIfNotExists(directoryPath: names.joined(separator: "/")) {
        }
        logOutPutStream = OutputStream.init(toFileAtPath: filePath, append: true)
        logOutPutStream.open()
    }
    deinit{
        logOutPutStream.close()
        logOutPutStream = nil
    }
    func _write(_ any:Any){
        print(any)
        let string = "[\(dateformatter.string(from: Date()))]\(any)\n"
        let data = string.data(using: .utf8)
        if let data = data {
            let bytes = [UInt8](data)
            logOutPutStream?.write( bytes, maxLength: data.count)
        }
    }

    
    func write(_ any:Any){
        print(any)
        let string = "[\(dateformatter.string(from: Date()))]\(any)\n"
        let data = string.data(using: .utf8)
        if let data = data {
            logData.append(data)
            if !logging {
                logging = true
                logOutPutStream?.open()
                privateLog()
            }
        }
    }
    private func privateLog(){
        let data = logData.removeFirst()
        let bytes = [UInt8](data)
        logOutPutStream?.write( bytes, maxLength: data.count)
        if logData.count > 0 {
            privateLog()
        }else {
//            var fileSize : UInt64 = 0
//            do {
//                let attr = try FileManager.default.attributesOfItem(atPath: filePath)
//                fileSize = attr[FileAttributeKey.size] as! UInt64
//                let dict = attr as NSDictionary
//                fileSize = dict.fileSize()
//            } catch {
//                print("Error: \(error)")
//            }
//            if fileSize > 1024 * 1024 {
//            }
            
            logOutPutStream?.close()
            logging = false
        }
    }
}
